package com.yungu.swift.lbs.trace.google;

import com.yungu.swift.utils.JsonUtils;
import com.yungu.swift.utils.StringUtils;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * Description
 *
 * @author Zerrion
 * @date 2018/1/19
 */
public class GoogleDistanceMatrixUtils {
    private static final Logger logger = LoggerFactory.getLogger(GoogleDistanceMatrixUtils.class);
    private static final String GOOGLE_MAPS_DISTANCE_MATRIX_URL = "https://maps.googleapis.com/maps/api/distancematrix/json?units=metric";
    private static final String ZTE_GOOGLE_MAPS_DISTANCE_MATRIX_API_KEY = "AIzaSyD0h5x8DkLwnxiCC1yJHRNu193N8Y6IX_4";

    /**
     * 通过地图计算估计里程
     *
     * @param origins      起点集
     * @param destinations 终点集
     * @return BigDecimal
     * @author Zerrion
     * @date 2018/1/9
     */
    public static BigDecimal getMinute(String origins, String destinations) {
        String result = invokeGoogleAPI(origins, destinations);
        if (StringUtils.isEmpty(result)) {
            return null;
        }
        try {
            Map map = JsonUtils.readValue(result, Map.class);
            if ("OK".equals(map.get("status"))) {
                Integer duration = (Integer) ((Map) ((Map) ((List) ((Map) ((List) map.get("rows")).get(0)).get("elements")).get(0)).get("duration")).get("value");
                //向下截取并加1，表示即时间为0，也需要1分钟
                return new BigDecimal(duration).divide(new BigDecimal(60), 0, BigDecimal.ROUND_DOWN).add(BigDecimal.ONE);
            } else {
                logger.error("获取谷歌时长-参数错误");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过地图计算估计里程
     *
     * @param origins      起点集
     * @param destinations 终点集
     * @return BigDecimal
     * @author Zerrion
     * @date 2018/1/9
     */
    public static BigDecimal getKilometre(String origins, String destinations) {
        String result = invokeGoogleAPI(origins, destinations);
        if (StringUtils.isEmpty(result)) {
            return null;
        }
        try {
            Map map = JsonUtils.readValue(result, Map.class);
            if ("OK".equals(map.get("status"))) {
                Map elements0 = (Map) ((List) ((Map) ((List) map.get("rows")).get(0)).get("elements")).get(0);
                if (elements0.containsKey("distance")) {
                    Integer distance = (Integer) ((Map) elements0.get("distance")).get("value");
                    return new BigDecimal(distance).divide(new BigDecimal(1000), 1, BigDecimal.ROUND_HALF_UP);
                } else {
                    logger.error("获取谷歌里程-ZERO_RESULTS");
                    return null;
                }
            } else {
                logger.error("获取谷歌里程-参数错误");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 调用谷歌API方法
     *
     * @param origins      起点集
     * @param destinations 终点集
     * @return String
     * @author Zerrion
     * @date 2018/1/9
     */
    private static String invokeGoogleAPI(String origins, String destinations) {
        String url = GOOGLE_MAPS_DISTANCE_MATRIX_URL + "&origins=" + origins + "&destinations=" + destinations;
        Map<String, Object> resultMap = GoogleRequestUtils.get(url, ZTE_GOOGLE_MAPS_DISTANCE_MATRIX_API_KEY);
        Integer status = (Integer) resultMap.get("status");
        String result = (String) resultMap.get("result");
        if (HttpStatus.SC_OK == status) {
            return result;
        } else {
            logger.error("请求谷歌DistanceMatrix接口-超时");
            return null;
        }
    }

}
